
define(["./dom", "./events", "./console", "./ajax", "./builder"], function(dom, events, console, ajax, builder) {
  var AFL_SELECTOR, FRAGMENT_TYPE;
  AFL_SELECTOR = "[data-container-type='core/AjaxFormLoop']";
  FRAGMENT_TYPE = "core/ajaxformloop-fragment";
  dom.onDocument("click", "" + AFL_SELECTOR + " [data-afl-behavior=remove]", function() {
    var afl, url,
      _this = this;
    afl = this.findParent(AFL_SELECTOR);
    if (!afl) {
      console.error("Enclosing element for AjaxFormLoop remove row link not found.");
      return false;
    }
    url = afl.attribute("data-remove-row-url");
    ajax(url, {
      parameters: {
        "t:rowvalue": this.attribute("data-afl-row-value")
      },
      success: function() {
        var fragment;
        fragment = _this.findParent("[data-container-type='" + FRAGMENT_TYPE + "']");
        return fragment.remove();
      }
    });
    return false;
  });
  dom.onDocument("click", "" + AFL_SELECTOR + " [data-afl-behavior=insert-before] [data-afl-trigger=add]", function() {
    var afl, insertionPoint, url,
      _this = this;
    afl = this.findParent(AFL_SELECTOR);
    insertionPoint = this.findParent("[data-afl-behavior=insert-before]");
    url = afl.attribute("data-inject-row-url");
    ajax(url, {
      success: function(response) {
        var content, newElement, _ref;
        content = (_ref = response.json) != null ? _ref.content : void 0;
        newElement = builder(insertionPoint.element.tagName, {
          "class": insertionPoint.element.className,
          "data-container-type": FRAGMENT_TYPE
        });
        newElement.update(content);
        insertionPoint.insertBefore(newElement);
        return newElement.trigger(events.zone.didUpdate);
      }
    });
    return false;
  });
  return null;
});
